﻿using System;
using System.Configuration;
using System.Web;
using Cms.Application.WebFramework.Presenters;
using Cms.Application.WebFramework.Views;
using Cms.Domain;
using Page = System.Web.UI.Page;

namespace Cms.Web.Framework.Infrastructure
{
    public class MediaHandler : Page, IMediaHandlerView
    {
        private MediaHandlerPresenter _presenter;
        private RequestDetails _requestDetails;

        #region IMediaHandlerView Members

        public MediaFile MediaFile
        {
            get { return _requestDetails != null && _requestDetails.MediaFile != null ? _requestDetails.MediaFile : null; }
        }
        
        public string PhysicalFilePath
        {
            get { return Server.MapPath(MediaFile.GetVirtualPath()); }
        }

        public void SetContentType(string value)
        {
            Response.ContentType = value;
        }

        public void AddHeader(string name, string value)
        {
            Response.AddHeader(name, value);
        }

        public void InsertOutputCacheEntry()
        {
            int duration = int.Parse(ConfigurationManager.AppSettings["MediaOutputCacheDuration"]);
            Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
            Response.Cache.VaryByParams["file"] = true;
            Response.Cache.SetExpires(DateTime.Now.AddSeconds(duration));
            Response.Cache.SetMaxAge(new TimeSpan(DateTime.Now.AddSeconds(duration).Ticks));
            Response.Cache.SetValidUntilExpires(true);
            Response.Cache.SetLastModified(HttpContext.Current.Timestamp);
            Response.AddCacheItemDependency(_requestDetails.FoldersAndPage);
        }

        public int UserId
        {
            get { return _requestDetails.UserID; }
        }

        public int AdministratorId
        {
            get { return _requestDetails.AdministratorID; }
        }

        public void SetStatusCode(int value)
        {
            Response.StatusCode = value;    
        }

        public void WriteFileToResponse(string virtualPath)
        {
            Response.WriteFile(virtualPath);
        }

        #endregion

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            _requestDetails = (RequestDetails)HttpContext.Current.Items["RequestDetails"];
            _presenter = new MediaHandlerPresenter(this);
            Response.ClearContent();
            Response.ClearHeaders();
            _presenter.ProcessFile();
            Response.End();
        }
    }
}